﻿using FileImportSystem2.Db.Entities;
using Microsoft.VisualBasic;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FileImportSystem2.Services
{
    internal class dbMatchServer : IDisposable
    {
        private readonly string _dbPath;
        private readonly string _dateMonth;
        private readonly string _dbFd = AppConfig.dbMonFd;
        private readonly string _dbMainPath = AppConfig.dbMainPath;
        private readonly IProgress<string>? _progress;
        private readonly SQLiteConnection _db = null!;
        private readonly SQLiteConnection _dbMain = null!;
        public bool _isInit = true;
        public string _initError = string.Empty;


        #region 实现 IDisposable 接口
        //IDisposable是 .NET 中的一个重要接口，它提供了一种​​确定性的资源释放机制​​，主要用于管理和释放非托管资源
        //.NET 的垃圾回收器（GC）能自动管理托管内存的释放，但它无法自动释放非托管资源。非托管资源是指不受 CLR（公共语言运行时）直接管理的资源
        //如果这些资源不及时释放，会导致内存泄漏和资源耗尽。IDisposable接口通过 Dispose()方法让开发者能够​​显式地、及时地​​释放这些资源
        private bool _disposed = false;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    // 分离附加的数据库
                    if (IsDatabaseAttached(_db, "MainDb"))
                    {
                        _db.Execute("DETACH DATABASE MainDb");
                    }

                    if (IsDatabaseAttached(_db, "LastDb"))
                    {
                        _db.Execute("DETACH DATABASE LastDb");
                    }

                    // 释放托管资源
                    _db?.Close();
                    _db?.Dispose();
                    _dbMain?.Close();
                    _dbMain?.Dispose();
                }
                _disposed = true;
            }
        }
        #endregion

        #region 构造函数
        public dbMatchServer(string dateMonth, IProgress<string>? progress = null)
        {
            _dateMonth = dateMonth;
            _dbPath = Path.Combine(_dbFd, _dateMonth + ".db");
            if (progress != null) { _progress = progress; }
            if (!File.Exists(_dbPath))
            {
                _isInit = false;
                _initError = $"{_dateMonth}数据库读取{_dbPath}不存在,请先导入";
                _progress?.Report(_initError);
                return;
            }
            if (!File.Exists(_dbMainPath))
            {
                _isInit = false;
                _initError = $"主数据库读取{_dbMainPath}不存在,请先导入";
                _progress?.Report(_initError);
                return;
            }

            try
            {
                _db = new(_dbPath);
                _dbMain = new(_dbMainPath);
            }
            catch (Exception ex)
            {
                _isInit = false;
                _initError = $"数据库打开失败，原因：{ex.Message}";
                _progress?.Report(_initError);
                return;
            }

        }
        #endregion

        #region 数据库初始化-创建索引/关联主数据库
        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <param name="isMatchInit"></param>
        public bool dbInit(bool isMatchInit = false)
        {
            DateTime dtUpdate = DateTime.Now; // 记录开始时间
            if (!_isInit)
            {
                _progress?.Report($"数据库初始化失败，原因：{_initError}");
                return false;
            }


            // 添加 索引 提升查询效率
            // senderdata   
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_SenderData_isMatched ON SenderData(isMatched);");
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_SenderData_扫描人 ON SenderData(扫描人);");
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_SenderData_单号 ON SenderData(单号);");
            // shenzhoudata
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_shenzhoudata_单号 ON shenzhoudata(单号);");
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_shenzhoudata_Is发件仓Matched ON shenzhoudata(Is发件仓Matched);");
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_shenzhoudata_Is分部Matched ON shenzhoudata(Is分部Matched);");
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_shenzhoudata_结算对象 ON shenzhoudata(结算对象);");
            // outboundinvoicedata
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_OutboundInvoiceData_IsMatched ON OutboundInvoiceData(IsMatched);");
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_OutboundInvoiceData_单号 ON OutboundInvoiceData(单号);");
            // CenterTransferFeeData
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_CenterTransferFeeData_IsMatched ON CenterTransferFeeData(IsMatched);");
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_CenterTransferFeeData_单号 ON CenterTransferFeeData(单号);");
            // UnMatchedData
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_UnMatchedData_单号 ON UnMatchedData(单号);");
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_UnMatchedData_结算对象 ON UnMatchedData(结算对象);");
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_UnMatchedData_发件仓 ON UnMatchedData(发件仓);");
            _db.Execute("CREATE INDEX IF NOT EXISTS idx_UnMatchedData_分部 ON UnMatchedData(分部);");
            // maindb
            _dbMain!.Execute("CREATE INDEX IF NOT EXISTS idx_SenderMatch_扫描人 ON SenderMatch(扫描人);");
            _dbMain.Execute("CREATE INDEX IF NOT EXISTS idx_ShenzhouMatch_结算对象 ON ShenzhouMatch(结算对象);");
            _progress?.Report("数据库初始化完成");

            // 初始化数据库匹配
            if (isMatchInit)
            {
                // 初始化 发件数据
                dtUpdate = DateTime.Now;
                _progress?.Report("初始化匹配状态为未匹配状态");
                _db.Execute("update SenderData set isMatched = 0,发件仓 = ''");
                _db.Execute("update shenzhoudata set 发件仓 = '',分部 = '',Is发件仓Matched = 0,Is分部Matched=0");
                _db.Execute("update OutboundInvoiceData set IsMatched = 0, 结算对象 = '' , 分部 = '' ");
                _db.Execute("update CenterTransferFeeData set IsMatched = 0, 结算对象 = '' , 分部 = '' ");
                _progress?.Report($"发件数据初始化完成,耗时{(DateTime.Now - dtUpdate).ToString()}");
            }
            // 关联 主数据库
            if (!AttachDatabaseWithVerification(_db, _dbMainPath, "MainDb"))
            {
                _isInit = false;
                _initError = "主数据库关联失败";
                _progress?.Report(_initError);
                return false;
            }
            //
            return true;
        }
        #endregion

        #region 附加数据库方法
        private bool IsDatabaseAttached(SQLiteConnection db, string aliasName)
        {
            var attachedDbs = db.Query<DatabaseInfo>("PRAGMA database_list;");
            return attachedDbs.Any(d => d.name.Equals(aliasName, StringComparison.OrdinalIgnoreCase));
        }

        private bool AttachDatabaseWithVerification(SQLiteConnection db, string dbPath, string aliasName, bool isShowSuccInfo = false)
        {

            try
            {
                // 0. 如果已经附加，则先分离
                if (IsDatabaseAttached(db, aliasName))
                {
                    db.Execute($"DETACH DATABASE {aliasName}");
                }
                // 1. 执行附加命令
                string attachSql = $@"ATTACH DATABASE '{dbPath}' AS {aliasName}";
                db.Execute(attachSql);

                // 2. 验证附加是否成功
                bool isSuccess = IsDatabaseAttached(db, aliasName);

                if (isSuccess)
                {

                    _progress?.Report($"数据库 {aliasName} 附加成功");

                    if (isShowSuccInfo)
                    {
                        // 3. 进一步验证：尝试查询
                        try
                        {
                            var testResult = db.Query<object>($"SELECT name FROM {aliasName}.sqlite_master LIMIT 1");
                            _progress?.Report($"数据库 {aliasName} 验证通过，包含 {testResult.Count} 个对象");
                        }
                        catch (Exception ex)
                        {
                            _progress?.Report($"警告：数据库附加成功但查询测试失败: {ex.Message}");
                        }
                    }


                }
                else
                {
                    _progress?.Report($"数据库 {aliasName} 附加失败");
                }

                return isSuccess;
            }
            catch (Exception ex)
            {
                _progress?.Report($"附加数据库时出错: {ex.Message}");
                return false;
            }
        }
        #endregion

        #region 匹配数据库

        // 添加异步方法
        public async Task MatchDataAsync(int months, bool isMatchInit = false)
        {
            await Task.Run(() => dbMatch(months, isMatchInit));
        }

        public void dbMatch(int nMonth, bool isMatchInit = false)
        {
            if (!_isInit)
            {
                _progress?.Report($"数据库初始化失败，原因：{_initError}");
                return;
            }


            _progress?.Report("开始更新数据");
            DateTime dt = DateTime.Now; // 记录开始时间
            DateTime dtUpdate = DateTime.Now; // 记录开始时间

            if (!dbInit(isMatchInit)) { return; }

            // 定义变量

            #region 废弃的更新方案
            //if (false)
            //{
            //    progress?.Report($"开始按扫描人匹配发件数据...");
            //    SenderMatch[] SenderMatchs = dbMain.Table<SenderMatch>().ToArray();
            //    progress?.Report($"发件数据需更新的记录数: {totalRows}，匹配规则数{SenderMatchs.Length}");

            //    for (int i = 0; i < SenderMatchs.Length; i++)
            //    {
            //        string sql = $"update SenderData set 发件仓='{SenderMatchs[i].分部}',isMatched = 1 where 扫描人='{SenderMatchs[i].扫描人}' and isMatched = 0 ";
            //        int rows = db.Execute(sql);
            //        updateRows += rows;
            //        if (rows > 0)
            //        {
            //            progress?.Report($"更新{rows}行数据，扫描人:{SenderMatchs[i].扫描人}，分部:{SenderMatchs[i].分部},进度:{100 * updateRows / totalRows}%");
            //        }
            //    }
            //    progress?.Report($"发件数据更新完成，共耗时 {(DateTime.Now - dt).ToString()}，更新{updateRows}行数据,剩余{totalRows - updateRows}条。");
            //}
            #endregion

            // 更新发件数据
            dbMatch_SenderData();

            // 更新神州明细
            dbMatch_ShenzhouData(nMonth);

            // 更新出港账单
            dbMatch_OutboundData();

            // 更新中心中转费
            dbMatch_CenterTransferFeeData();

            _progress?.Report($"匹配完成,耗时 {(DateTime.Now - dtUpdate).ToString()}");
        }
        #endregion

        #region 匹配方法

        /// <summary>
        /// 更新发件数据
        /// </summary>
        /// <param name="step_id"></param>
        /// <returns></returns>
        private bool dbMatch_SenderData(string step_id = "1")
        {

            // 定义变量
            int totalRows = 0;
            int updateRows = 0;
            DateTime dtUpdate = DateTime.Now;
            // 更新 发件仓 -- 根据扫描人从匹配表-发件数据匹配分部
            try
            {
                _progress?.Report($"{step_id}.0.开始匹配发件数据");
                _progress?.Report($"{step_id}.1.按扫描人匹配发件数据...");
                totalRows = _db!.ExecuteScalar<int>("select count(*) from SenderData where isMatched = 0");
                _progress?.Report($"{step_id}.1.需匹配{totalRows}条");

                // 更新 发件仓 -- 根据扫描人从匹配表-发件数据匹配分部
                _db.RunInTransaction(() =>
                {
                    updateRows += _db.Execute("update SenderData " +
                    "set 发件仓 = (select 分部 from maindb.sendermatch where sendermatch.扫描人 = SenderData.扫描人),isMatched  = 1 " +
                    "where exists ( select 1 from maindb.sendermatch where sendermatch.扫描人 = SenderData.扫描人) and isMatched  =0");
                });
                totalRows -= updateRows;

                _progress?.Report($"{step_id}.1.发件数据更新完成，耗时 {(DateTime.Now - dtUpdate).ToString()}，更新{updateRows}条数据,剩余{totalRows}条。");

                // 更新发件仓 -- 根据单号从补充库读取发件仓
                dtUpdate = DateTime.Now;
                _db.RunInTransaction(() =>
                {
                    updateRows = _db.Execute("update SenderData " +
                    "set 发件仓 = a.发件仓,isMatched  = 1 " +
                    "from UnMatchedData a " +
                    "where isMatched=0 and SenderData.单号 = a.单号 and a.发件仓 <>''");
                });
                totalRows -= updateRows;

                _progress?.Report($"{step_id}.发件数据-补充库更新完成，耗时 {(DateTime.Now - dtUpdate).ToString()}，更新{updateRows}条数据,剩余{totalRows}条。");
            }
            catch (Exception ex)
            {
                _progress?.Report($"{step_id}.发件数据更新失败，原因：{ex.Message}");
                return false;
            }


            return true;
        }

        /// <summary>
        /// 更新神州明细
        /// </summary>
        /// <param name="nMonth"></param>
        /// <param name="step_id"></param>
        /// <returns></returns>
        private bool dbMatch_ShenzhouData(int nMonth = 2, string step_id = "2")
        {
            // 定义变量
            int totalRows = 0;
            int updateRows = 0;
            DateTime dtUpdate = DateTime.Now;
            string tableName = "shenzhoudata";//{tableName}
            // 更新 发件仓 -- 根据扫描人从匹配表-发件数据匹配分部
            try
            {
                // 更新 神州数据
                _progress?.Report($"{step_id}.0.开始匹配神州数据...");
                #region 根据运单号从发件数据匹配发件仓
                // 更新 发件仓 -- 根据运单号从发件数据匹配发件仓
                _progress?.Report($"{step_id}.1.按单号自发件数据匹配发件仓...");
                totalRows = _db.ExecuteScalar<int>($"select count(*) from {tableName} where Is发件仓Matched = 0 ");
                _progress?.Report($"{step_id}.1.需匹配{totalRows}条");
                _progress?.Report($"{step_id}.1.1.匹配当月数据...");
                dtUpdate = DateTime.Now;

                string sql = $"update {tableName} " +
                            $"set 发件仓 = (select 发件仓 from LastDb.SenderData where LastDb.SenderData.单号 = {tableName}.单号),Is发件仓Matched  = 1 " +
                            $"where  Is发件仓Matched = 0 and exists ( select 1 from LastDb.SenderData where LastDb.SenderData.单号 = {tableName}.单号) ";

                _db.RunInTransaction(() =>
                {
                    updateRows = _db.Execute(sql.Replace("LastDb.", ""));
                });

                totalRows -= updateRows;

                _progress?.Report($"{step_id}.1.1.当月数据匹配完成，耗时{(DateTime.Now - dtUpdate).ToString()}，更新{updateRows}条数据,剩余{totalRows}条。");

                // 更新历史月份数据

                dbMatchHistory(sql, step_id, nMonth);


                // 更新神州数据(发件仓)-自补充库
                dtUpdate = DateTime.Now;
                _db.RunInTransaction(() =>
                {
                    updateRows = _db.Execute($"update {tableName} " +
                    "set 发件仓 = a.发件仓,Is发件仓Matched  = 1 " +
                    "from UnMatchedData a " +
                    $"where Is发件仓Matched = 0 and {tableName}.单号 = a.单号 and a.发件仓 <>''");
                });
                totalRows -= updateRows;

                _progress?.Report($"{step_id}.1.神州数据-发件仓-补充库更新完成，耗时 {(DateTime.Now - dtUpdate).ToString()}，更新{updateRows}条数据,剩余{totalRows}条。");


                #endregion

                #region 根据结算对象从匹配表-神州数据匹配匹配分部
                // 更新 分部 -- 根据结算对象从匹配表-神州数据匹配匹配分部
                _progress?.Report($"{step_id}.2.按结算对象从匹配表-神州数据匹配匹配分部...");
                totalRows = _db.ExecuteScalar<int>($"select count(*) from {tableName} where Is分部Matched = 0 ");
                _progress?.Report($"{step_id}.2.需匹配{totalRows}条");
                dtUpdate = DateTime.Now;
                _db.RunInTransaction(() =>
                {
                    // 处理特殊结算对象
                    string[] dxList = AppConfig.shenzhouDxList;
                    foreach (string dx in dxList)
                    {
                        var dx_rows = _db.Execute($"update {tableName} set 结算对象 = 揽收业务员 where 结算对象 like '%{dx}%'");
                        _progress?.Report($"{step_id}.2.1.{dx}更新结算对象{dx_rows}条为揽收业务员");
                    }
                    updateRows = _db.Execute($"update {tableName} " +
                                    $"set 分部 = (select 分部 from maindb.shenzhoumatch where shenzhoumatch.结算对象 = {tableName}.结算对象),Is分部Matched  = 1 " +
                                    $"where exists ( select 1 from maindb.shenzhoumatch where shenzhoumatch.结算对象 = {tableName}.结算对象) and Is分部Matched = 0 ");

                });
                totalRows -= updateRows;
                _progress?.Report($"{step_id}.2.2.分部数据更新完成，耗时 {(DateTime.Now - dtUpdate).ToString()}，更新{updateRows}条数据,剩余{totalRows }条。");


                // 更新神州数据(分部)-自补充库
                dtUpdate = DateTime.Now;
                _db.RunInTransaction(() =>
                {
                    updateRows = _db.Execute($"update {tableName} " +
                    "set 分部 = a.分部,Is分部Matched  = 1 " +
                    "from UnMatchedData a " +
                    $"where Is分部Matched = 0 and {tableName}.单号 = a.单号 and a.分部 <>''");
                });
                totalRows -= updateRows;
                _progress?.Report($"{step_id}.1.神州数据-分部-补充库更新完成，耗时 {(DateTime.Now - dtUpdate).ToString()}，更新{updateRows}条数据,剩余{totalRows}条。");


                #endregion
            }
            catch (Exception ex)
            {
                _progress?.Report($"{step_id}.神州数据更新失败，原因：{ex.Message}");
                return false;
            }

            return true;

        }

        /// <summary>
        /// 更新出港账单_出港运单明细
        /// </summary>
        /// <param name="step_id"></param>
        /// <returns></returns>
        private bool dbMatch_OutboundData(int nMonth = 2, string step_id = "3")
        {
            // 定义变量
            int totalRows = 0;
            int updateRows = 0;
            DateTime dtUpdate = DateTime.Now;
            string tableName = "OutboundInvoiceData";
            // 更新 结算对象、分部 -- 根据运单号从神州明细匹配结算对象、分部
            try
            {
                // 更新 神州数据
                _progress?.Report($"{step_id}.0.开始匹配出港账单...");
                #region 根据运单号从神州明细匹配结算对象、分部
                // 更新 发件仓 -- 根据运单号从神州明细匹配结算对象、分部
                _progress?.Report($"{step_id}.1.按单号自神州明细匹配结算对象、分部...");
                totalRows = _db.ExecuteScalar<int>("select count(*) from OutboundInvoiceData where IsMatched = 0 ");
                _progress?.Report($"{step_id}.1.需匹配{totalRows}条");
                dtUpdate = DateTime.Now;

                // 更新完整匹配数据
                string sql = $"UPDATE {tableName} " +
                              "SET 结算对象 = sd.结算对象, " +
                              "分部 = sd.分部, " +
                              "IsMatched = sd.Is分部Matched " +
                              "FROM LastDb.ShenzhouData sd " +
                              $"WHERE {tableName}.单号 = sd.单号 AND {tableName}.IsMatched = 0 ";

                _db.RunInTransaction(() =>
                {
                    updateRows = _db.Execute(sql.Replace("LastDb.", "")); // 去掉sql中 LastDb. 即为本月的sql
                });

                _progress?.Report($"{step_id}.1.当前匹配行数仅为匹配行数,部分匹配信息不完整,实际需完善数量看最后结果。");
                _progress?.Report($"{step_id}.1.当月数据匹配完成，耗时{(DateTime.Now - dtUpdate).ToString()}，更新{updateRows}条数据,剩余{totalRows - updateRows}条。");
                // 更新历史月份数据
                dbMatchHistory(sql, step_id, nMonth);
                //
                long unMatchRows = _db.ExecuteScalar<long>($"select count(*) from {tableName} where IsMatched = 0");

                _progress?.Report($"{step_id}.数据匹配完成，耗时{(DateTime.Now - dtUpdate).ToString()}，更新{totalRows - unMatchRows}条数据，剩余需匹配{unMatchRows}条。");


                // 更新出港账单-自补充库
                dtUpdate = DateTime.Now;
                _db.RunInTransaction(() =>
                {
                    updateRows = _db.Execute($"update {tableName} " +
                    "set 结算对象 = a.结算对象,分部=a.分部,IsMatched  = 1 " +
                    "from UnMatchedData a " +
                    $"where IsMatched = 0 and {tableName}.单号 = a.单号 and a.分部 <>'' and  a.结算对象 <>''");
                });
                unMatchRows -= updateRows;
                _progress?.Report($"{step_id}.出港账单-补充库(结算对象和分部均不为空)更新完成，耗时 {(DateTime.Now - dtUpdate).ToString()}，更新{updateRows}条数据,剩余{unMatchRows}条。");

                #endregion

            }
            catch (Exception ex)
            {
                _progress?.Report($"{step_id}.出港账单更新失败，原因：{ex.Message}");
                return false;
            }

            return true;

        }

        /// <summary>
        /// 更新中心中转费
        /// </summary>
        /// <param name="step_id"></param>
        /// <returns></returns>
        private bool dbMatch_CenterTransferFeeData(int nMonth = 2, string step_id = "4")
        {
            // 定义变量
            int totalRows = 0;
            int updateRows = 0;
            DateTime dtUpdate = DateTime.Now;
            string tableName = "CenterTransferFeeData";
            // 更新 结算对象、分部 -- 根据运单号从神州明细匹配结算对象、分部
            try
            {
                // 更新 神州数据
                _progress?.Report($"{step_id}.0.开始匹配中心中转费...");
                #region 根据运单号从神州明细匹配结算对象、分部
                // 更新 发件仓 -- 根据运单号从神州明细匹配结算对象、分部
                _progress?.Report($"{step_id}.1.按单号自神州明细匹配结算对象、分部...");
                totalRows = _db.ExecuteScalar<int>($"select count(*) from {tableName} where IsMatched = 0 ");
                _progress?.Report($"{step_id}.1.需匹配{totalRows}条");
                dtUpdate = DateTime.Now;


                string sql = $"UPDATE {tableName} " +
                              "SET 结算对象 = sd.结算对象, " +
                              "分部 = sd.分部, " +
                              "IsMatched = Is分部Matched " +
                              "FROM LastDb.ShenzhouData sd " +
                              $"WHERE {tableName}.单号 = sd.单号 AND {tableName}.IsMatched = 0 ";

                _db.RunInTransaction(() =>
                {
                    updateRows = _db.Execute(sql.Replace("LastDb.", "")); // 去掉sql中 LastDb. 即为本月的sql
                });

                _progress?.Report($"{step_id}.1.当前匹配行数仅为匹配行数,部分匹配信息不完整,实际需完善数量看最后结果。");
                _progress?.Report($"{step_id}.1.当月数据匹配完成，耗时{(DateTime.Now - dtUpdate).ToString()}，更新{updateRows}条数据,剩余{totalRows - updateRows}条。");
                // 更新历史月份数据
                dbMatchHistory(sql, step_id, nMonth);
                //
                long unMatchRows = _db.ExecuteScalar<long>($"select count(*) from {tableName} where IsMatched = 0");

                _progress?.Report($"{step_id}.数据匹配完成，耗时{(DateTime.Now - dtUpdate).ToString()}，更新{totalRows - unMatchRows}条数据，剩余需匹配{unMatchRows}条。");

                // 更新中心中转费-自补充库
                dtUpdate = DateTime.Now;
                _db.RunInTransaction(() =>
                {
                    updateRows = _db.Execute($"update {tableName} " +
                    "set 结算对象 = a.结算对象,分部=a.分部,IsMatched  = 1 " +
                    "from UnMatchedData a " +
                    $"where IsMatched = 0 and {tableName}.单号 = a.单号 and a.分部 <>'' and  a.结算对象 <>''");
                });
                unMatchRows -= updateRows;
                _progress?.Report($"{step_id}.中心中转费-补充库(结算对象和分部均不为空)更新完成，耗时 {(DateTime.Now - dtUpdate).ToString()}，更新{updateRows}条数据,剩余{unMatchRows}条。");

                #endregion


            }
            catch (Exception ex)
            {
                _progress?.Report($"{step_id}.中心中转费更新失败，原因：{ex.Message}");
                return false;
            }

            return true;

        }

        /// <summary>
        /// 匹配历史月份数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="step_id"></param>
        /// <param name="nMonth"></param>
        /// <returns></returns>
        private bool dbMatchHistory(string sql, string step_id, int nMonth = 2)
        {
            // 历史月份等于0 等于不使用历史数据
            if (nMonth == 0) { return true; }
            // 定义变量
            int totalRows = 0;
            int updateRows = 0;
            DateTime dtUpdate = DateTime.Now;
            // 更新历史数据
            _progress?.Report($"{step_id}.1.2.匹配前{nMonth}月数据...");
            for (int i = 1; i <= nMonth; i++)
            {
                _progress?.Report($"{step_id}.1.2.{i}.匹配前{i}月发件数据...");
                dtUpdate = DateTime.Now;
                string dbLastPath = FileNameServer.getDbPathByMonth(_dateMonth, i);// 获取前i个月的数据库路径
                if (!File.Exists(dbLastPath))
                {
                    _progress?.Report($"{step_id}.1.2.{i}.前{i}月数据库不存在:{dbLastPath}");
                    continue;
                }
                else
                {
                    // 附加数据库
                    if (!AttachDatabaseWithVerification(_db, dbLastPath, "LastDb"))
                    {
                        _progress?.Report($"{step_id}.1.2.{i}.数据库{dbLastPath}关联失败，继续其他月");
                        continue;
                    }
                    else
                    {
                        // 执行更新
                        _db.RunInTransaction(() =>
                        {
                            updateRows = _db.Execute(sql);
                        });

                        totalRows -= updateRows;
                        _progress?.Report($"{step_id}.1.2.{i}.前{i}月数据匹配完成，耗时{(DateTime.Now - dtUpdate).ToString()}，更新{updateRows}条数据,剩余{totalRows}条。");
                    }

                    // 分离数据库
                    _db.Execute("DETACH DATABASE LastDb");
                }
            }


            return true;
        }

        #endregion
    }
}
